<template>
    <!-- form 查询表单 -->
    <el-form :model="user" ref="formRef" label-width="auto" label-position="right" style="padding-bottom: 10px;">
        <el-row :gutter="20">
            <el-col :span="6">
                <el-form-item label="昵称" prop="nc">
                    <el-input v-model="user.nc" placeholder="请输入用户昵称" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="user.phone" placeholder="请输入手机号" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="店铺数" prop="shopCount">
                    <el-input v-model="user.shopCount" placeholder="请输入店铺数" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="用户状态" prop="status">
                    <el-input v-model="user.status" placeholder="请输入正常/禁用" clearable/>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="24">
                <el-button type="primary" @click="doList">查询</el-button>
                <el-button type="default" @click="reset">重置</el-button>
            </el-col>
        </el-row>
    </el-form>
    <!-- table 表格 -->
    <el-table :data="userData" border style="width: 100%">
        <el-table-column prop="id" label="用户ID"/>
        <el-table-column prop="userName" label="用户名"/>
        <el-table-column prop="pwd" label="密码"/>
        <el-table-column prop="avatar" label="头像"/>
        <el-table-column prop="nc" label="昵称"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column prop="sex" label="性别"/>
        <el-table-column prop="createTime" label="注册时间"/>
        <el-table-column prop="status" label="账号状态">
            <!-- 使用模板语法转换数字为文字 -->
            <template #default="scope">
                {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </template>
        </el-table-column>
        <el-table-column prop="shopCount" label="店铺数量"/>
        <el-table-column label="操作" width="250">
            <template #default="scope">
                <el-button type="primary" @click="showDetailUser(scope.row)">详情</el-button>
                <el-button type="warning" @click="showUpdateDialog(scope.row)">更新</el-button>
                <el-button type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div style="margin-top: 10px; text-align: right;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
    </div>
    <!--    更新 dialog-->
    <el-dialog v-model="updateDialogVisible" title="更新用户" width="40%" top="2vh" destroy-on-close>
        <update-user
            ref="updateUserRef"
            @closeDialog="updateDialogVisible = false">
        </update-user>
    </el-dialog>

    <!--    详情 dialog-->
    <detail-user ref="detailUserRef"></detail-user>

</template>

<script setup lang="ts">
import {nextTick, onMounted, ref} from 'vue'
import axios from "axios";
import { ElMessage } from 'element-plus'
import DetailUser  from "./DetailUser.vue";
import UpdateUser from "./UpdateUser.vue";
// 分页参数
const pageNum = ref(1); // 当前页码（默认第1页）
const pageSize = ref(5); // 每页条数（默认5条）
const total = ref(0); // 总记录数（从后端获取）

const user = ref({
    nc: '',
    phone: '',
    status: '',
    shopCount: ''
});

// 重置查询条件
const reset = () => {
    user.value = {
        nc: '',
        phone: '',
        status: '',
        shopCount: ''
    };
};

const userData = ref([]);

// 页面加载时执行查询
onMounted(() => {
    doList();
})

// 查询用户列表
const doList = async () => {
    try {
        let statusNum = user.value.status;
        // 处理中文状态转换
        if (statusNum === '正常') {
            statusNum = 1; // 1代表正常
        } else if (statusNum === '禁用') {
            statusNum = 0; // 0代表禁用
        } else if (statusNum && !['0', '1'].includes(statusNum)) {
            // 处理无效输入
            ElMessage.warning('状态只能输入：正常、禁用、0或1');
            return;
        }

        const { data } = await axios.get('/api/shop/userMS', {
            params: {
                nc: user.value.nc,
                status: statusNum, // 使用转换后的状态值
                phone: user.value.phone,
                shopCount: user.value.shopCount,
                pageNum: pageNum.value,
                pageSize: pageSize.value
            }
        });

        // 打印完整响应，方便调试
        console.log("后端返回的完整数据：", data);

        // 直接使用返回的数据
        userData.value = data.records || [];
        total.value = data.total || 0;

        if (userData.value.length === 0) {
            ElMessage.info('未查询到符合条件的数据');
        }
    } catch (error) {
        console.error("请求失败！原因：", error);
        ElMessage.error('网络错误，查询失败');
        userData.value = [];
        total.value = 0;
    }
}

// 每页条数变化时触发
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    pageNum.value = 1;
    doList();
};

// 当前页码变化时触发
const handleCurrentChange = (val: number) => {
    pageNum.value = val;
    doList();
};
//--------------------------- 更新 对话框 ---------------------------
const updateDialogVisible = ref(false);
const updateUserRef = ref();
const showUpdateDialog = (obj)=>{
    updateDialogVisible.value = true;
    nextTick(()=>{
        updateUserRef.value.handleUpdateData(obj);
    })
}
//--------------------------- 详显 页面---------------------------
const detailUserRef = ref();
const showDetailUser = (obj)=>{
    detailUserRef.value.handleDetailData(obj);
}
//--------------------------- 删除 ---------------------------
const deleteUser = async (id) => {
    const {data} = await axios.delete(`/api/shop/userMS/${id}`);
    if(data > 0){
        doList() ;
        ElMessage.success('删除成功');
    }else{
        ElMessage.error('删除失败');
    }
}
</script>
<style scoped>

</style>
